package core;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import core.util.Const;


/**
 * 验证码工具类
 * @author qiwx
 *
 */
@SuppressWarnings("serial")
public class KeyCodeServlet extends HttpServlet {
	private Font mFont = new Font("Times New Roman", Font.PLAIN, 20);
	public static Map<String, String> imgMap = new HashMap<String, String>();
	public static int contNo = 4;
	Color getRanColor(int fc, int bc){
		Random random = new Random();
		if(fc>255) fc = 255;
		if(bc>255) bc = 255;
		int r = fc + random.nextInt(bc - fc);//
		int g = fc + random.nextInt(bc - fc);//
		int b = fc + random.nextInt(bc - fc);
		return new Color(r,g,b);
	}
	
	/**
	 * Constructor of the object.
	 */
	public KeyCodeServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); 
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
	  String key = request.getParameter("a");
		response.setHeader("Pragm", "No-cache");
		response.setHeader("Cache-control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		int width = 75, height = 22;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		//Color c = new Color(200,255,0,0);
		g.setColor( getRanColor(200,250) ); //填充颜色getRanColor(200,250)
		g.fillRect(1, 1, width-1, height-1);
		g.setColor(new Color(102,102,102));//边框的颜色
		g.drawRect(0, 0, width-1, height-1);
		g.setFont(mFont);
		g.setColor(getRanColor(160,200));
		String sRand = "";
		for(int i=0; i<contNo; i++){      //一共显示6个数
		  int temp = random.nextInt(9) ;
		  sRand += String.valueOf(temp);
		  g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
		  g.drawString(String.valueOf(temp), 15*i+10, 16);  //string, x, y
		}
		HttpSession session = request.getSession();
		session.setAttribute(Const.CODE_IMG, sRand);
		imgMap.put(key, sRand);
		g.dispose();
		ImageIO.write(image, "jpeg", response.getOutputStream());
	}
	
	public void init() throws ServletException {
		super.init();
	}

	public void forward(String url , HttpServletRequest request,HttpServletResponse response)
      throws ServletException,IOException  {
      ServletContext sc = getServletConfig().getServletContext();
      RequestDispatcher rd = sc.getRequestDispatcher(url);
      rd.forward(request,response);
  }
}
